<template>
  <div>
    <div class="header">
      <el-form :inline="true" class="search-form">
        <el-form-item label="组别名称">
          <el-input v-model="searchParams.Name" placeholder="请输入组别名称" clearable @clear="handleSearch" />
        </el-form-item>
        <el-form-item label="类别">
          <el-input v-model="searchParams.Category" placeholder="请输入类别" clearable @clear="handleSearch" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchParams.IsActive" placeholder="请选择状态" style="width: 120px;" clearable
            @change="handleSearch">
            <el-option label="激活" value="Y" />
            <el-option label="失效" value="N" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="Search"> 搜索 </el-button>
        </el-form-item>
      </el-form>

    </div>
    <div class="actions">
      <el-button type="primary" @click="handleAddGroup">新增组别</el-button>
    </div>

    <el-table :data="groupList" border v-loading="loading" style="width: 100%"   default-align="center">
      <!-- <el-table-column prop="id" label="组别ID" width="180"></el-table-column> -->
      <el-table-column prop="Name" label="组别名称" align="center"></el-table-column>
      <el-table-column prop="Category" label="分类" align="center"></el-table-column>
      <el-table-column prop="IsActive" label="状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.IsActive === 'Y' ? 'success' : 'danger'">
            {{ scope.row.IsActive === 'Y' ? '有效' : '无效' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="Remark" label="备注" align="center"></el-table-column>
      <el-table-column prop="CreatedBy" label="创建人" align="center"></el-table-column>
      <el-table-column prop="CreatedAt" label="创建时间" align="center"></el-table-column>
      <el-table-column prop="ModifiedBy" label="修改人" align="center"></el-table-column>
      <el-table-column prop="ModifiedAt" label="修改时间" align="center"></el-table-column>


      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize" background="true"
        :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form :model="currentGroup" label-width="120px">
        <el-form-item label="组别名称">
          <el-input v-model="currentGroup.Name"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="currentGroup.Category" placeholder="请选择分类">
            <el-option label="权限组" value="权限组"></el-option>
            <el-option label="项目组" value="项目组"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="currentGroup.IsActive">
            <el-radio label="Y">有效</el-radio>
            <el-radio label="N">无效</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="currentGroup.Remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { GroupMaster } from '@/viewModel/system.ts'
import { getAllGroups, GetPageGroup, addGroup, updateGroup, deleteGroup } from '@/api/system/group'


    const groupList = ref<GroupMaster[]>([])
    const dialogVisible = ref(false)
    const isEditMode = ref(false)
    const dialogTitle = ref('新增组别')
    const currentGroup = ref<GroupMaster>({
      Id: 0,
      Name: '',
      Category: '',
      Remark: '',
      IsActive: 'Y',
      CreatedBy: '',
      CreatedAt: undefined,
      ModifiedBy: '',
      ModifiedAt: undefined
    })// 分页参数
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    const loading = ref(false)
    // 搜索参数
    const searchParams = reactive({
      Name: '',
      Category: '',
      IsActive: ''
    })
    // 分页大小变化
    const handleSizeChange = (size: number) => {
      pagination.pageSize = size
      fetchGroupsPage()
    }

    // 当前页变化
    const handleCurrentChange = (page: number) => {
      pagination.currentPage = page
      fetchGroupsPage()
    }
    // 搜索处理
    const handleSearch = () => {
      pagination.currentPage = 1
      fetchGroupsPage()
    }
    // 获取用户列表
    const fetchGroupsPage = async () => {
      try {
        loading.value = true
        const params = {
          ...searchParams,
        }
        debugger
        const res = await GetPageGroup( pagination.currentPage, pagination.pageSize,params)
        if (res.Code == 200 && res.Data != null) {
          groupList.value = res.Data.Data
          pagination.total = res.Data.TotalCount
        }

      } catch (error) {
        ElMessage.error('获取用户列表失败')
      } finally {
        loading.value = false
      }
    }
    const fetchGroups = async () => {
      try {
        const res = await getAllGroups()
        if (res.Code == 200 && res.Data != null) {
          groupList.value = res.Data
          console.table(groupList.value);
        }

      } catch (error) {
        ElMessage.error('获取组别列表失败')
      }
    }

    const handleAddGroup = () => {
      isEditMode.value = false
      dialogTitle.value = '新增组别'
      currentGroup.value = {
        Id: 0,
        Name: '',
        Category: '',
        Remark: '',
        IsActive: 'Y',
        CreatedBy: '',
        CreatedAt: undefined,
        ModifiedBy: '',
        ModifiedAt: undefined
      }
      dialogVisible.value = true
    }

    const handleEdit = (group: GroupMaster) => {
      isEditMode.value = true
      dialogTitle.value = '编辑组别'
      currentGroup.value = JSON.parse(JSON.stringify(group))
      dialogVisible.value = true
    }

    const handleDelete = (groupId: number) => {
      ElMessageBox.confirm('确定要删除该组别吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteGroup(groupId)
          ElMessage.success('删除成功')
          fetchGroups()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
    }

    const submitForm = async () => {
      try {
        if (isEditMode.value) {
          await updateGroup(currentGroup.value)
          ElMessage.success('更新成功')
        } else {
          await addGroup(currentGroup.value)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        fetchGroups()
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }

    onMounted(() => {
      handleSearch()
    })  
</script>

<style scoped>
.group-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
  padding-bottom: 5px;
  border-bottom: 1px solid #ebeef5;
}
.actions{
 margin-bottom: 5px;
}

   

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>